/*
 * Copyright 2012 GitHub Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.love.util;

import static android.graphics.Bitmap.Config.ARGB_8888;
import static android.graphics.Color.WHITE;
import static android.graphics.PorterDuff.Mode.DST_IN;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.Log;
import android.widget.ImageView;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

/**
 * Image utilities
 */
public class ImageUtils {

	private static final String TAG = "ImageUtils";

	/**
	 * Get a bitmap from the image path
	 * 
	 * @param imagePath
	 * @return bitmap or null if read fails
	 */
	public static Bitmap getBitmap(final String imagePath) {
		return getBitmap(imagePath, 1);
	}

	/**
	 * Get a bitmap from the image path
	 * 
	 * @param imagePath
	 * @param sampleSize
	 * @return bitmap or null if read fails
	 */
	public static Bitmap getBitmap(final String imagePath, int sampleSize) {
		final Options options = new Options();
		options.inDither = false;
		options.inSampleSize = sampleSize;

		RandomAccessFile file = null;
		try {
			file = new RandomAccessFile(imagePath, "r");
			return BitmapFactory.decodeFileDescriptor(file.getFD(), null,
					options);
		} catch (IOException e) {
			Log.d(TAG, e.getMessage(), e);
			return null;
		} finally {
			if (file != null)
				try {
					file.close();
				} catch (IOException e) {
					Log.d(TAG, e.getMessage(), e);
				}
		}
	}

	/**
	 * Get a bitmap from the image
	 * 
	 * @param image
	 * @param sampleSize
	 * @return bitmap or null if read fails
	 */
	public static Bitmap getBitmap(final byte[] image, int sampleSize) {
		final Options options = new Options();
		options.inDither = false;
		options.inSampleSize = sampleSize;
		return BitmapFactory.decodeByteArray(image, 0, image.length, options);
	}

	/**
	 * Get scale for image of size and max height/width
	 * 
	 * @param size
	 * @param width
	 * @param height
	 * @return scale
	 */
	public static int getScale(Point size, int width, int height) {
		if (size.x > width || size.y > height)
			return Math.max(Math.round((float) size.y / (float) height),
					Math.round((float) size.x / (float) width));
		else
			return 1;
	}

	/**
	 * Get size of image
	 * 
	 * @param imagePath
	 * @return size
	 */
	public static Point getSize(final String imagePath) {
		final Options options = new Options();
		options.inJustDecodeBounds = true;

		RandomAccessFile file = null;
		try {
			file = new RandomAccessFile(imagePath, "r");
			BitmapFactory.decodeFileDescriptor(file.getFD(), null, options);
			return new Point(options.outWidth, options.outHeight);
		} catch (IOException e) {
			Log.d(TAG, e.getMessage(), e);
			return null;
		} finally {
			if (file != null)
				try {
					file.close();
				} catch (IOException e) {
					Log.d(TAG, e.getMessage(), e);
				}
		}
	}

	/**
	 * Get size of image
	 * 
	 * @param image
	 * @return size
	 */
	public static Point getSize(final byte[] image) {
		final Options options = new Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeByteArray(image, 0, image.length, options);
		return new Point(options.outWidth, options.outHeight);
	}

	/**
	 * Get bitmap with maximum height or width
	 * 
	 * @param imagePath
	 * @param width
	 * @param height
	 * @return image
	 */
	public static Bitmap getBitmap(final String imagePath, int width, int height) {
		Point size = getSize(imagePath);
		return getBitmap(imagePath, getScale(size, width, height));
	}

	/**
	 * Get bitmap with maximum height or width
	 * 
	 * @param image
	 * @param width
	 * @param height
	 * @return image
	 */
	public static Bitmap getBitmap(final byte[] image, int width, int height) {
		Point size = getSize(image);
		return getBitmap(image, getScale(size, width, height));
	}

	/**
	 * Get bitmap with maximum height or width
	 * 
	 * @param image
	 * @param width
	 * @param height
	 * @return image
	 */
	public static Bitmap getBitmap(final File image, int width, int height) {
		return getBitmap(image.getAbsolutePath(), width, height);
	}

	/**
	 * Get a bitmap from the image file
	 * 
	 * @param image
	 * @return bitmap or null if read fails
	 */
	public static Bitmap getBitmap(final File image) {
		return getBitmap(image.getAbsolutePath());
	}

	/**
	 * Load a {@link Bitmap} from the given path and set it on the given
	 * {@link ImageView}
	 * 
	 * @param imagePath
	 * @param view
	 */
	public static void setImage(final String imagePath, final ImageView view) {
		setImage(new File(imagePath), view);
	}

	/**
	 * Load a {@link Bitmap} from the given {@link File} and set it on the given
	 * {@link ImageView}
	 * 
	 * @param image
	 * @param view
	 */
	public static void setImage(final File image, final ImageView view) {
		Bitmap bitmap = getBitmap(image);
		if (bitmap != null)
			view.setImageBitmap(bitmap);
	}

	/**
	 * Round the corners of a {@link Bitmap}
	 * 
	 * @param source
	 * @param radius
	 * @return rounded corner bitmap
	 */
	public static Bitmap roundCorners(final Bitmap source, final float radius) {
		int width = source.getWidth();
		int height = source.getHeight();

		Paint paint = new Paint();
		paint.setAntiAlias(true);
		paint.setColor(WHITE);

		Bitmap clipped = Bitmap.createBitmap(width, height, ARGB_8888);
		Canvas canvas = new Canvas(clipped);
		canvas.drawRoundRect(new RectF(0, 0, width, height), radius, radius,
				paint);
		paint.setXfermode(new PorterDuffXfermode(DST_IN));

		Bitmap rounded = Bitmap.createBitmap(width, height, ARGB_8888);
		canvas = new Canvas(rounded);
		canvas.drawBitmap(source, 0, 0, null);
		canvas.drawBitmap(clipped, 0, 0, paint);

		source.recycle();
		clipped.recycle();

		return rounded;
	}

	/**
	 * 图片配置
	 * 
	 * @param drawableId
	 *            默认图/错误图
	 * @return
	 */
	public static DisplayImageOptions getOptions(int drawableId) {
		return new DisplayImageOptions.Builder().showImageOnLoading(drawableId)
				.showImageForEmptyUri(drawableId).showImageOnFail(drawableId)
				.cacheInMemory(true).cacheOnDisc(true)
				.resetViewBeforeLoading(true)
				.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
	}
}
